package com.lagou.config;

import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * 自定义初始化器
 * 实现web.xml配置
 * 完成AppConfig的注册，并基于java代码的方式初始化DispatcherServlet
 */
public class MyWebApplicationInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // 1. 通过注解的方式初始化Spring的上下文
        AnnotationConfigWebApplicationContext annotationConfigApplicationContext = new AnnotationConfigWebApplicationContext();
        // 2. 注册Spring的配置类
        annotationConfigApplicationContext.register(AppConfig.class);
        annotationConfigApplicationContext.refresh();
        // 3.基于java代码的方式初始化DispatcherServlet
        DispatcherServlet dispatcherServlet = new DispatcherServlet(annotationConfigApplicationContext);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", dispatcherServlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/app/*");

        System.out.println("MyWebApplicationInitializer... finished");
    }

}
